package com.ruoyi.system.service.impl;

import cn.hutool.json.JSONUtil;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dyvmsapi20170525.Client;
import com.aliyun.dyvmsapi20170525.models.SingleCallByTtsRequest;
import com.aliyun.dyvmsapi20170525.models.SingleCallByTtsResponse;
import com.aliyun.dyvmsapi20170525.models.SingleCallByTtsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.system.domain.VoiceDetail;
import com.ruoyi.system.service.IAliVoiceService;
import com.ruoyi.system.service.IAsyncDetailService;
import com.ruoyi.system.service.IVoiceDetailService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AliVoiceServiceImpl implements IAliVoiceService {

    @Autowired
    private IAsyncDetailService asyncDetailService;

    @Autowired
    private IVoiceDetailService voiceDetailService;

    //产品请求url
    private static final String END_POINT = "dyvmsapi.aliyuncs.com";

    @Value("${notification.voice.keyId:}")
    private String keyId;

    @Value("${notification.voice.secret:}")
    private String secret;

    @Value("${notification.voice.template.alarm:}")
    private String alarmTemplate;

    @Override
    @Async
    public void send(JSONObject request, String tid) {
        Long companyId = request.getLong("companyId");
        String receiver = request.getString("receiver");
        String type = request.getString("type");
        String template = null;
        if ("alarm".equals(type)) {
            template = alarmTemplate;
        } else {
            // TODO: [zy]
            return;
        }
        JSONObject parameters = request.getJSONObject("parameters");
        Config config = new Config();
        config.setAccessKeyId(keyId);
        config.setAccessKeySecret(secret);
        config.setEndpoint(END_POINT);
        boolean error = false;
        SingleCallByTtsResponse response = null;
        try {
            Client client = new Client(config);
            SingleCallByTtsRequest singleCallByTtsRequest = new SingleCallByTtsRequest();
            singleCallByTtsRequest.setCalledNumber(receiver);
            singleCallByTtsRequest.setTtsCode(alarmTemplate);
            singleCallByTtsRequest.setTtsParam(parameters.toJSONString());
            response = client.singleCallByTts(singleCallByTtsRequest);
            log.info("{}", response);
        } catch (Exception e) {
            log.error("语音发送失败。异常原因{}", e.getMessage());
            error = true;
            asyncDetailService.update(tid, 2, "语音发送失败。异常原因:" + e.getMessage());
        }
        VoiceDetail detail = new VoiceDetail();
        if (response != null && response.getBody() != null) {
            SingleCallByTtsResponseBody data = response.getBody();
            log.info("语音发送返回结果：{}", data);
            detail.setBizId(data.getCallId());
            detail.setRequestId(data.getRequestId());
            detail.setCode(data.getCode());
            detail.setMessage(data.getMessage());
        } else {
            if (!error) {
                error = true;
                asyncDetailService.update(tid, 2, "语音发送失败。失败原因：没有获取到语音返回值");
            }
        }
        detail.setPhoneNumber(receiver);
        detail.setTemplateParam(parameters.toJSONString());
        detail.setTemplateCode(template);
        detail.setType(type);
        detail.setCompanyId(companyId);
        detail.setCreateTime(new Date());
        detail.setTid(tid);
        voiceDetailService.create(detail);
        if (!error) {
            asyncDetailService.update(tid, 1, JSON.toJSONString(response));
        }
    }
}
